import { Button,Input  } from 'antd';
import React, { useEffect, useState } from 'react';
import { DownOutlined,LikeOutlined,DislikeOutlined,CommentOutlined,ShareAltOutlined} from '@ant-design/icons';
import { $getImg } from '../../api/getImgapi';
import { $getCommentCount, $getComments,$newComment,$SharePost } from '../../api/postapi';
import MyNotification from "../../components/MyNotification/MyNotification";
import Comment from '../comment/comment';
import {useNavigate} from "react-router-dom";
const { TextArea } = Input;

const Post1 = ({ post ,avater}) => {
    //跳转页面导航
    const navigate = useNavigate();
    //通知框状态
    const [notiMsg, setNotiMsg] = useState({ type: "", description: "" });
    //显示评论状态
    const [showComments, setShowComments] = useState(false);
    //获取帖子的评论
    const[comments,setComments]=useState([]);
    //阅读全文按钮的状态设置
    const [read,setRead]=useState(true);
    //为了讲useEffect中获取的图片数据在return中获得
    const [data, setData] = useState(null);
    //获得一条帖子评论的数量
    const [commentcount,SetCommentcount]=useState(0);
    //阅读全文的点击事件
    const essay=()=>{
        setRead(!read);
    }
    //获取评论的信息
    const fetchComments = async () => {
        try {
            const response = await $getComments({postId:post.postId.toString()});
            if(response.code===1){
                setComments(response.data); // 假设响应的数据结构是一个数组
            }
        } catch (error) {
            console.error('Error fetching comments:', error);
        }
    };
    //获取输入框评论内容的实时更新
    const [comment1, setComment1] = useState('');
//输入框的回调函数，及时更新输入框的内容
    const handleCommentChange = (event) => {
        setComment1(event.target.value);
    };

    //生成新的评论
    const handlePublish = async() => {
        const response = await $newComment({postId:post.postId.toString(),content:comment1});
        if (response.code) {
            setNotiMsg({ type: "success", description: response.message});
        } else {
            setNotiMsg({ type: "error", description: response.message })
        }
        setComment1('');
    };


    //获取帖子评论的数量
    const fetchCommentsCount = async () => {
        try {
            const response = await $getCommentCount({postId:post.postId.toString()});
            if(response.code===1){
                SetCommentcount(response.data); // 假设响应的数据结构是一个数组
            }
        } catch (error) {
            console.error('Error fetching CommentsCount:', error);
        }
    };
    //获取帖子头像
    const getImg=async ()=>{
        console.log(post.studentId);
        const response= await $getImg({ studentId: post.studentId.toString() });
            if(response.code===1){
                setData(response.data);
            }
    }
    useEffect(()=>{
        //获取帖子头像
        getImg();
        // 使用Date对象解析原始日期时间字符串
        const originalDateTime = new Date(post.createdAt);
        // 获取所需的日期时间格式，例如 "YYYY-MM-DDTHH:MM"
        setFormattedDateTime( originalDateTime.toISOString().slice(0, 16))
    },[])
    //每次添加评论后都会自动刷新
    useEffect(()=>{
        // fetchComments();
        fetchCommentsCount();//获取评论数量
    },[comments])
    //点击评论后的按钮
    const Comt=()=>{
        fetchComments();//获取评论信息
        setShowComments(!showComments);//显示按钮的状态是否评论已近点开
    }
    //点击头像函数
    const handleAvatarClick = (studentId) => {
        navigate(`/layout/othermine/${studentId}`);
    };
    //分享帖子
    const Share=async ()=>{
        const response =await $SharePost({postId:post.postId.toString(),content:'赞同'});
    }
    //转换时间
    const [formattedDateTime,setFormattedDateTime]=useState('');


    return (
        <div style={{margin:'30px',borderBottom:'4px solid rgb(221, 240, 238)'}}>
                    <div>
                        <h2>
                                <span>{post.title}</span>
                        </h2>
                    </div>
                        <div className="AuthorInfo" style={{display:'flex',marginTop:'10px'}}>

                    <div className="css-1gomreu">
                    <img src={`data:image/jpeg;base64,${data}`}  alt="获取图片失败" style={{ width:'50px',height:'50px'}} onClick={()=>{handleAvatarClick(post.studentId)}}/>
                    </div>

                            <div className="css-1gomreu" style={{fontWeight:'bold',marginTop:'15px',marginLeft:'10px'}}>
                                {post.nickname}
                            </div>

                        </div>

                    <div className='post-content'>
          <span>
            {read ? post.content.substring(0, 200) : post.content}
              {post.content.length > 200&& (
                  <Button
                      type="link"
                      onClick={essay}
                      style={{ color: 'rgb(138, 216, 210)'}}
                  >
                      {read ? '阅读全文' : '收起全文'}
                      <DownOutlined  />
                  </Button>

              )}
          </span>
                        <div className='ContentItem-actions' style={{display:'flex'}}>

                <Button icon={<LikeOutlined />} style={{border: 'none'}}>{post.likeNum}</Button>
                <Button icon={<DislikeOutlined /> } style={{border: 'none'}}>{post.dislike}</Button>
                <Button icon={<CommentOutlined />} style={{border: 'none'}} onClick={Comt}>{!showComments?commentcount+'条评论':'收起评论'}</Button>
              <Button icon={<ShareAltOutlined />} style={{border: 'none'}} onClick={Share}></Button>
                        </div>
                    </div>


            <div>

            </div>
            {showComments && (

                <div>
                    <div style={{ display: "flex", alignItems: "center", marginTop:"20px", marginBottom:"20px"}}>
                        <img src={`data:image/jpeg;base64,${avater}`}  alt="获取图片失败" style={{ width:'50px',height:'50px'}}/>

                        <textarea
                            value={comment1}
                            onChange={handleCommentChange}
                            placeholder="欢迎参加讨论"
                            style={{width:'80vw'}}
                            autoSize={{
                                minRows: 2,
                                maxRows: 6,
                            }}
                        />
                        <Button type="primary" onClick={handlePublish} style={{backgroundColor:'rgb(178, 234, 230)',width:'60px', height:"40px"}}>
                            发布
                        </Button>

                    </div>
                    <h3>{commentcount+"条评论"}</h3>
                    {comments.map((comment, index) => (
                        <Comment key={index} comment={comment} avater={avater}/>
                    ))}
                </div>
            )}
            <MyNotification notiMsg={notiMsg} />
        </div>
    );
};

export default Post1;
